import UIKit

class AudioMessageViewModel: CardMessageViewModel, AttachmentLoadingViewModel {
    
    let length: String
    let waveform: Waveform
    
    var progress: Double?
    var showPlayIconAfterFinished: Bool = true
    var operationButtonStyle: NetworkOperationButton.Style = .expired
    var operationButtonIsHidden = false
    var playbackStateIsHidden = true
    
    var automaticallyLoadsAttachment: Bool {
        return true
    }
    
    var mediaStatus: String? {
        get {
            return message.mediaStatus
        }
        set {
            message.mediaStatus = newValue
            if newValue != MediaStatus.PENDING.rawValue {
                progress = nil
            }
            updateOperationButtonStyle()
            updateButtonsHidden()
        }
    }
    
    override var size: CGSize {
        return CGSize(width: contentWidth + leftLeadingMargin + leftTrailingMargin + 48 + 10, height: 72)
    }
    
    private let contentWidth: CGFloat

    override init(message: MessageItem, style: Style, fits layoutWidth: CGFloat) {
        let duration = Int(message.mediaDuration ?? 0)
        let seconds = Int(round(Double(duration) / millisecondsPerSecond))
        length = mediaDurationFormatter.string(from: TimeInterval(seconds)) ?? ""
        contentWidth = WaveformView.estimatedWidth(forDurationInSeconds: seconds)
        self.waveform = Waveform(data: message.mediaWaveform, durationInSeconds: seconds)
        super.init(message: message, style: style, fits: layoutWidth)
        updateOperationButtonStyle()
        updateButtonsHidden()
    }
    
    func beginAttachmentLoading() {
        
    }
    
    func cancelAttachmentLoading(markMediaStatusCancelled: Bool) {
        
    }
    
    private func updateButtonsHidden() {
        if case .finished = operationButtonStyle {
            operationButtonIsHidden = true
            playbackStateIsHidden = false
        } else {
            operationButtonIsHidden = false
            playbackStateIsHidden = true
        }
    }

}
